<?php

namespace App\Http\Middleware;

use App\Model\Role;
use App\Model\User;
use Closure;

class CheckAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $action = \Route::current()->getActionName();
        list($class, $method) = explode('@', $action);
        $controller = substr(strrchr($class, '\\'), 1);
        $url =$controller.'@'.$method;
        //排除哪些方法不用验证
        if(in_array($url,["IndexController@index",'LoginController@logout','IndexController@welcome'])){
            return $next($request);
        }
        //1.获取session 中用户信息
        $userinfo = session()->get('userinfo');
        //排除哪些用户可以直接通过
        if(in_array($userinfo['user_name'],['admin'])){
            return $next($request);
        }
        //2.获取用户所拥有权限
        $role = User::find($userinfo['user_id'])->role;
        $user_per = [];
        foreach ($role as $v){
            $permission = Role::find($v->id)->permission;
            foreach ($permission as $val){
                $user_per[] = $val->per_url;
            }
        }
        //3.比对当前控制器@方法是否在里面
        if(in_array($url,$user_per)){
            return $next($request);
        }else{
            return redirect('/admin/noaccess');
        }

    }
}
